<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\controller\ExpertSms;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use PDO;
use think\Cache;
use think\Env;

/**
 * 项目管理
 *
 * @icon fa fa-circle-o
 */
class Project extends Backend
{

    /**
     * Project模型对象
     * @var \app\admin\model\Project
     */
    protected $model = null;
    protected $projectexpertmodel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Project;
        $this->projectexpertmodel = new \app\admin\model\Projectexpert;


        $pid = Db::name('dictionary')->where('code', 10004)->where('status', 1)->value('id');
        $type_data = Db::name('dictionary')->where('pid', $pid)->where('status', 1)->select();
        foreach ($type_data as $k => $v) {
            $type_data[$k]['name'] = $v['title'];
            $type_data[$k]['id'] = $v['title'];
        }
        $this->view->assign('type_data', $type_data);

        $pid1 = Db::name('dictionary')->where('code', 10000)->where('status', 1)->value('id');
        $expert_type = Db::name('dictionary')->where('pid', $pid1)->where('status', 1)->select();
        $this->view->assign('expert_type', $expert_type);

        $pid2 = Db::name('dictionary')->where('code', 10001)->where('status', 1)->value('id');
        $expert_zc = Db::name('dictionary')->where('pid', $pid2)->where('status', 1)->select();
        $this->view->assign('expert_zc', $expert_zc);

        $pid3 = Db::name('dictionary')->where('code', 10002)->where('status', 1)->value('id');
        $expert_ku = Db::name('dictionary')->where('pid', $pid3)->where('status', 1)->select();
        $this->view->assign('expert_ku', $expert_ku);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        $exacTime = Env::get('task.exec_time');
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        $filter = json_decode($this->request->get("filter"), true);
        $op     = json_decode($this->request->get("op"), true);

        if (isset($filter['province'])) {
            $province = $filter['province'];
            unset($filter['province'], $op['province']);
            $filter['province'] =  $province;
            $op['province']     = '=';
            $this->request->get(["filter" => json_encode($filter), 'op' => json_encode($op)]);
        }

        if (isset($filter['city'])) {
            $city = $filter['city'];
            unset($filter['city'], $op['city']);
            $filter['city'] = $city;
            $op['city']     = '=';
            $this->request->get(["filter" => json_encode($filter), 'op' => json_encode($op)]);
        }

        if (isset($filter['area'])) {
            $area = $filter['area'];
            unset($filter['area'], $op['area']);
            $filter['area'] = $area;
            $op['area']     = '=';
            $this->request->get(["filter" => json_encode($filter), 'op' => json_encode($op)]);
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit)->each(function ($item) use ($exacTime) {
                $last_draw_time = $item['last_draw_time'];
                if (empty($last_draw_time)) {
                    $last_draw_time = $item['createtime'];
                }

                if (time() - $item['open_time'] >= 900) {
                    $item['is_kb'] = true;
                } else {
                    $item['is_kb'] = false;
                }

                // if (time() - $last_draw_time > $exacTime && $item['status'] == 2) {
                //     $item['is_bc'] = true;
                // } else {
                //     $item['is_bc'] = false;
                // }
                return $item;
            });
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }



    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $isExit = Db::name('project')->where('code', $params['code'])->find();
        if (!empty($isExit)) {
            $this->error('项目编号已存在');
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;

        $isExit = Db::name('project')->where('id', '<>', $ids)->where('code', $params['code'])->find();
        if (!empty($isExit)) {
            $this->error('项目编号已存在');
        }

        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function getDictionary()
    {
        $pid3 = Db::name('dictionary')->where('code', 10002)->where('status', 1)->value('id');
        $expert_ku = Db::name('dictionary')->where('pid', $pid3)->where('status', 1)->select();
        $this->success('', '', $expert_ku);
    }

    public function hasDuplicateRows($array)
    {
        $rowsAsStrings = array_map('implode', array_map(function ($row) {
            return $row;
        }, $array)); // 将所有行转换为字符串
        $uniqueRows = array_unique($rowsAsStrings); // 获取唯一的行字符串数组
        return count($uniqueRows) !== count($rowsAsStrings); // 如果唯一行的数量不等于原始行的数量，则存在重复行
    }

    /**
     * 计算单个分组可用专家数量
     */
    public function signeExpert()
    {
        $params = $this->request->post();
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $rowData = $params['rowData'];
        $ids = !empty($params['ids']) ? $params['ids'] : '';


        $tempExcludeIds = [];
        $expert_result_ids = json_decode($params['expert_result_ids'], true);
        $c_index = $params['c_index'];
        $expert_result_ids[$c_index] = '';
        $expert_result_ids = array_values(array_filter($expert_result_ids));
        $tempStrIds = '';
        foreach ($expert_result_ids as $k => $v) {
            $tempStrIds .= ',' . $v;
        }
        $tempStrIds = trim($tempStrIds, ',');
        $tempExcludeIds = array_filter(explode(',', $tempStrIds));


        $excludeIDs = []; //需要排除的专家id数组
        if (!empty($ids)) { //查询已抽取的记录
            $alredyData = Db::name('projectexpert')->where(['project_id' => $ids, 'status' => '2'])->where('deletetime', NULL)->field('expert_id')->select();
            $alredyData = !empty($alredyData) ? array_unique(array_column($alredyData, 'expert_id')) : [];
            $excludeIDs = $alredyData;
        } 
        $excludeIDs = array_merge($tempExcludeIds,$excludeIDs);
       
        $rst = $this->getSignleExpert($rowData, false, $excludeIDs);
        $already_ids = array_column($rst, 'id');



        return json(['code' => 1, 'msg' => '查询成功', 'data' => $already_ids, 'expert_result_ids' => $tempExcludeIds]);
    }

    public function extractCqFun($basic, $total_cq_num, $is_wz_params)
    {
        //格式化数据
        foreach ($basic['major'] as $index => $name) {
            $expertids = $basic['expertids'][$index] ?? '';
            $major = $basic['major'][$index] ?? '';
            $pb_province = $basic['pb_province'][$index] ?? '';
            $pb_city = $basic['pb_city'][$index] ?? '';
            $pb_area = $basic['pb_area'][$index] ?? '';
            // $expert_zc = $basic['expert_zc'][$index] ?? 0;
            $expert_ku = $basic['expert_ku'][$index] ?? 0;
            $cq_num = $basic['cq_num'][$index] ?? 0;

            $total_cq_num = $total_cq_num + $cq_num;
            if (empty($major) || empty($pb_province) || empty($pb_city) || empty($pb_area)) {
                $is_wz_params = false;
            }

            // 构造单行关联数组
            $items[] = [
                'major'     => $major,
                'expertids' => $expertids,
                'pb_province'    => $pb_province,
                'pb_city' => $pb_city,
                'pb_area'     => $pb_area,
                // 'expert_zc'    => $expert_zc,
                'expert_ku' => $expert_ku,
                'cq_num'     =>   $cq_num
            ];
            $items1[] = [
                'major'     => $major,
                'expertids' => $expertids,
                'pb_province'    => $pb_province,
                'pb_city' => $pb_city,
                'pb_area'     => $pb_area,
                // 'expert_zc'    => $expert_zc,
                'expert_ku' => $expert_ku,
            ];
        }
        return [$items, $items1, $total_cq_num, $is_wz_params];
    }

    /**
     * 专家抽取
     *<!-- [{"major":"","pb_province":"","pb_city":"","pb_area":"","expert_zc":"","expert_ku":"","cq_num":""}] -->
     * @return string
     * @throws \think\Exception
     */

    public function extract($ids = '')
    {
        if (false === $this->request->isPost()) {

            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            if (empty($row['extraction_conditions'])) {
                $json = json_encode([["major" => "", "pb_province" => "", "pb_city" => "", "pb_area" => "", "expert_zc" => "", "expert_ku" => "", "cq_num" => ""]], JSON_UNESCAPED_UNICODE);
            } else {
                $json = json_encode(json_decode($row['extraction_conditions'], true), JSON_UNESCAPED_UNICODE);
            }
            $this->view->assign('extraction_conditions', $json);
            $this->view->assign('ids', $ids);
            return $this->view->fetch();
        }
        $params = $this->request->post('');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        //抽取条件
        $basic = $params['item'];
        $ids = $params['ids'];

        $is_bc = !empty($params['is_bc']) ? true : false;
        $project_info = $this->model->get($ids);
        $cq_rst = [];
        if (empty($basic)) {
            $this->error("抽取条件设置有误");
        }
        $is_wz_params = true;
        $total_cq_num = 0;
        list($items, $items1, $total_cq_num, $is_wz_params) = $this->extractCqFun($basic, $total_cq_num, $is_wz_params);
        if ($this->hasDuplicateRows($items1)) {
            $this->error("抽取条件不能重复");
        }

        if (!$is_wz_params) {
            return json(['code' => 0, 'msg' => '请选择完整抽取条件']);
        }
        if ($total_cq_num <= 0) {
            return json(['code' => 0, 'msg' => '抽取专家数量有误，请重新抽取']);
        }
        if ($total_cq_num > $project_info['num']) {
            return json(['code' => 0, 'msg' => '抽取专家数量大于项目需求专家人数' . $project_info['num'] . '人，请重新抽取']);
        }
        //判断是否存在上传专家 开始抽取 
        if ($is_bc) {
            $already_cq_num = Db::name('projectexpert')->where('project_id', $ids)->where('deletetime', NULL)->where('status', 2)->count();
            if (($project_info['num'] - $already_cq_num) != $total_cq_num) {
                return json(['code' => 0, 'msg' => '补抽专家数量不正确，应为' . ($project_info['num'] - $already_cq_num) . '人，请重新抽取']);
            }

            $cq_rst = $this->cq_extract($items, $project_info['expert_ids'], $ids); //抽取结果
        } else {
            $cq_rst = $this->cq_extract($items, $project_info['expert_ids']); //抽取结果
        }
        if (empty($cq_rst)) {
            Db::rollback();
            return json(['code' => 0, 'msg' => '未抽取到专家数据，请重新选择抽取条件']);
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            //修改项目抽取条件配置 
            $result = $this->model->allowField(true)->where('id', $ids)->update(['extraction_conditions' => json_encode($basic)]);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }

        $expert_ids_arr = [];
        if (!empty($cq_rst)) {
            foreach ($cq_rst as $k => $v) {
                foreach ($v['extract_rst'] as $kk => $vv) {
                    array_push($expert_ids_arr, ['id' => $vv['id'], 'name' => $vv['name']]);
                }
            }
        }

        $expert_ids_arr_idss = !empty($expert_ids_arr) ? array_column($expert_ids_arr, 'id') : [];
        $allExpert = Db::name('expert')->where('id', 'not in', $expert_ids_arr_idss)->where('deletetime', NULL)->limit(80 - count($expert_ids_arr))->orderRaw('RAND()')->field('id,name')->select();
        foreach ($allExpert as $k => $v) {
            $allExpert[$k]['name'] = $this->desensitizeName($v['name']);
        }
        $realExpert = array_merge($allExpert, $expert_ids_arr);
        if (empty($expert_ids_arr)) {
            return json(['code' => 0, 'msg' => '未找到符合条件的专家，请重新抽取']);
            exit;
        } else {
            return json(['code' => 1, 'msg' => '抽取完成', 'data' => ['allExpert' => $realExpert, 'cq_rst' => $expert_ids_arr]]);
            exit;
        }
    }

    /**
     * 补抽
     */
    public function expert_bc($ids = '')
    {
        // Cache::set('alreadyIds','');
        if (false === $this->request->isPost()) {
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $items = [];
            $extraction_conditions = empty($row['extraction_conditions']) ? [] : json_decode($row['extraction_conditions'], true);
            $expert_ids = $row['expert_ids'];
            $total_cq_num = 0;
            $is_wz_params = true;
            list($items, $items1, $total_cq_num, $is_wz_params) = $this->extractCqFun($extraction_conditions, $total_cq_num, $is_wz_params);

            //判断是否存在上传专家 开始抽取 
            $cq_rst = $this->cq_extract($items, $expert_ids, $ids); //抽取结果   
            $this->view->assign('ids', $ids);
            $this->view->assign('cq_rst', $cq_rst);
            return $this->view->fetch();
        }
    }

    /**
     * 抽取完成
     */
    public function confirmCq()
    {
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $projectexpert = [];
        $chooseExpert = !empty($params['result_ids']) ? $params['result_ids'] : '';
        if (empty($chooseExpert)) {
            $this->error("未确认专家信息，请重新抽取");
        }
        $chooseExpert = explode(',', $chooseExpert);
        $chooseExpert = array_filter($chooseExpert);

        $ids = $params['ids'];
        $is_bc = isset($params['is_bc']) ? true : false;

        foreach ($chooseExpert as $k => $v) {
            array_push($projectexpert, ['expert_id' => $v, 'project_id' => $ids]);
        }

        $uniqueArr = array_unique($projectexpert, SORT_REGULAR);
        $projectexpert = array_values($uniqueArr);

        $project_info =  $this->model->where(['id' => $ids])->where('status', 'in', '1,2')->find();
        if (empty($project_info)) {
            $this->error("该项目目前不能抽取专家");
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            // $this->projectexpertmodel->where('project_id', $ids)->delete(); 
            $result = $this->projectexpertmodel->allowField(true)->saveAll($projectexpert);
            if ($is_bc) {
                $y_num = $this->projectexpertmodel->where('project_id', $ids)->group('expert_id')->count();
                $this->model->allowField(true)->where('id', $ids)->update(['status' => 2, 'last_draw_time' => time(), 'is_show_bc' => 1, 'y_num' => $y_num]);
            } else {
                $this->model->allowField(true)->where('id', $ids)->update(['status' => 2, 'sms_sendtime' => time(), 'y_num' => count($projectexpert)]);
            }
            Db::commit();
            //给专家发送短信
            $expertSms = new ExpertSms();
            $expertSms->sendExpertSms($project_info, $projectexpert);
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 上传专家
     */
    public function upload_expert()
    {
        $params = $this->request->post();
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $ids = $params['ids'];
        $pids = $params['pid'];
        $expert_num = count($ids); //上传专家的数量必须和项目的需求人数一致
        $row = $this->model->get($pids);
        if (!$row) {
            return json(['code' => 0, 'msg' => '项目不存在']);
            exit;
        }
        if ($row['num'] != $expert_num) {
            return json(['code' => 0, 'msg' => '专家数量只能选' . $row['num'] . '位']);
            exit;
        }
        $ids_str = implode(',', $ids);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            //修改项目抽取条件配置
            $result = $this->model->allowField(true)->where('id', $pids)->update(['expert_ids' => $ids_str]);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            return json(['code' => 0, 'msg' => '专家上传失败']);
            exit;
        }
        if ($result === false) {
            return json(['code' => 0, 'msg' => '专家上传失败']);
            exit;
        }
        return json(['code' => 1, 'msg' => '上传成功', 'data' => '']);
        exit;
    }

    //数组随机拆分
    public function randomSplit($array, $n)
    {
        shuffle($array); // 随机打乱数组
        $chunks = array_chunk($array, ceil(count($array) / $n)); // 分割成大约N份
        return $chunks;
    }

    /**
     * 抽取专家
     */
    public function cq_extract($data, $expert_ids = '', $pid = '')
    {
        $excludeIDs = []; //需要排除的专家id数组
        if (!empty($pid)) { //查询已抽取的记录
            $alredyData = Db::name('projectexpert')->where(['project_id' => $pid, 'status' => '2'])->where('deletetime', NULL)->field('expert_id')->select();
            $alredyData = !empty($alredyData) ? array_unique(array_column($alredyData, 'expert_id')) : [];
            $excludeIDs = $alredyData;
        }
        if (!empty($expert_ids)) {
            if (!empty($excludeIDs)) {
                $extract_rst = Db::name('expert')->where('id', 'in', $expert_ids)->where('id', 'not in', $excludeIDs)->where('deletetime', NULL)->field('id, name')->select();
            } else {
                $extract_rst = Db::name('expert')->where('id', 'in', $expert_ids)->where('deletetime', NULL)->field('id, name')->select();
            }

            foreach ($extract_rst as $kk => $vv) {
                $extract_rst[$kk]['name'] = $this->desensitizeName($vv['name']);
            }
            $chunkData = $extract_rst ? $this->randomSplit($extract_rst, count($data)) : [];
            foreach ($data as $k => $v) {
                if (!empty($chunkData[$k])) {
                    $data[$k]['extract_rst'] = $chunkData[$k];
                } else {
                    $data[$k]['extract_rst'] = [];
                }
            }
        } else {
            foreach ($data as $k => $v) {
                $extract_rst = $this->getSignleExpert($v, true, $excludeIDs);
                foreach ($extract_rst as $kk => $vv) {
                    $extract_rst[$kk]['name'] = $this->desensitizeName($vv['name']);
                }
                $data[$k]['extract_rst'] = $extract_rst;
            }
        }
        return $data;
    }


    public function getSignleExpert($v, $islimit = false, $excludeIDs = [])
    {
        if (empty($v['major']) || empty($v['pb_province']) || empty($v['pb_city']) || empty($v['pb_area'])) {
            return [];
        }
        $expertids = !empty($v['expertids']) ? $v['expertids'] : [];
        $where = [
            // 'professional' => $v['major'],
            // 'position' => $v['expert_zc'],
            'expert_data' => !empty($v['expert_ku'])?$v['expert_ku']:'',
            'province' => $v['pb_province'],
            'city' => $v['pb_city'],
            'area' => $v['pb_area']
        ];
        $where = array_filter($where);
        if ($islimit) {
            $extract_rst = Db::name('expert')->where('id', 'in', $expertids)->orderRaw('RAND()')->where('deletetime', NULL)->limit($v['cq_num'])->field('id, name')->select();
            // if (!empty($excludeIDs)) {
            //     // $extract_rst = Db::name('expert')->where('find_in_set(:major,professional)', ['major' => $v['major']])->where($where)->where('id', 'not in', $excludeIDs)->orderRaw('RAND()')->where('deletetime', NULL)->limit($v['cq_num'])->field('id, name')->select();
            // } else {
            //     // $extract_rst = Db::name('expert')->where('find_in_set(:major,professional)', ['major' => $v['major']])->where($where)->orderRaw('RAND()')->where('deletetime', NULL)->limit($v['cq_num'])->field('id, name')->select();
            // }
        } else {
            if (!empty($excludeIDs)) {
                $extract_rst = Db::name('expert')->where('find_in_set(:major,professional)', ['major' => $v['major']])->where($where)->where('id', 'not in', $excludeIDs)->orderRaw('RAND()')->where('deletetime', NULL)->field('id, name')->select();
            } else {
                $extract_rst = Db::name('expert')->where('find_in_set(:major,professional)', ['major' => $v['major']])->where($where)->orderRaw('RAND()')->where('deletetime', NULL)->field('id, name')->select();
            }
        }
        return $extract_rst;
    }


    /**
     * 姓名脱敏函数
     * @param string $name 中文姓名
     * @return string 脱敏后的姓名
     */
    public function desensitizeName($name)
    {
        // 常见复姓列表（可根据需要补充）
        $compoundSurnames = [
            '欧阳',
            '司徒',
            '司马',
            '上官',
            '诸葛',
            '宇文',
            '尉迟',
            '申屠',
            '夏侯',
            '皇甫',
            '长孙',
            '慕容',
            '东方',
            '端木',
            '独孤',
            '南宫',
            '万俟',
            '闻人',
            '夏侯',
            '子车'
        ];

        $length = mb_strlen($name, 'UTF-8');
        if ($length === 0) {
            return '';
        }

        // 默认姓氏长度为1
        $surnameLength = 1;

        // 检查前两个字符是否为复姓
        if ($length >= 2) {
            $firstTwoChars = mb_substr($name, 0, 2, 'UTF-8');
            if (in_array($firstTwoChars, $compoundSurnames)) {
                $surnameLength = 2;
            }
        }

        // 提取姓氏和名字
        $surname = mb_substr($name, 0, $surnameLength, 'UTF-8');
        $givenName = mb_substr($name, $surnameLength, null, 'UTF-8');

        // 替换名字为星号
        $givenNameStars = str_repeat('*', mb_strlen($givenName, 'UTF-8'));

        return $surname . $givenNameStars;
    }

    /**
     * 详情
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;



        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
